package library.common.view.recyclerview;

import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;

/**
 * @author Created by qiang.hou on 2019/1/17.
 * @version 1.0
 */
public class ScrollSpeedLinearLayoutManger extends LinearLayoutManager {
    /**
     * milliseconds it takes to scroll one pixel
     */
    private float MILLISECONDS_PER_INCH = 0.03f;

    public ScrollSpeedLinearLayoutManger(Context context) {
        super(context);
    }

    public ScrollSpeedLinearLayoutManger(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext()) {
                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        return ScrollSpeedLinearLayoutManger.this
                                .computeScrollVectorForPosition(targetPosition);
                    }

                    // This returns the milliseconds it takes to scroll one pixel.
                    @Override
                    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                        return MILLISECONDS_PER_INCH;
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }

    /**
     * @param milliSeconds milliseconds it takes to scroll one pixel.
     */
    public void setSmoothScrollSpeed(float milliSeconds) {
        MILLISECONDS_PER_INCH = milliSeconds;
    }
}
